from rest_framework import serializers
from aweiuser import models
from django.contrib.auth import get_user_model

User = get_user_model()


class UserInfoSerializer(serializers.Serializer):
    """
    用户信息序列化
    建议实现其他方法，否则会有警告
    """
    username = serializers.CharField(required=True, error_messages={
        "code": "2001",
        "required": "用户名校验失败",
        "max_length": "用户名长度不能超过20个字符",
    })

    password = serializers.CharField(required=True, error_messages={
        "code": "2001",
        "required": "密码校验失败"
    })

    email = serializers.CharField(required=True, error_messages={
        "code": "2001",
        "required": "邮箱校验失败"
    })

    def create(self, validated_data):
        """
        实现create方法
        """
        return models.UserInfo.objects.create(**validated_data)


class UserLoginSerialzer(serializers.Serializer):
    username = serializers.CharField(required=True)
    password = serializers.CharField(required=True)


class UserModelSerializer(serializers.ModelSerializer):
    """
    访问统计序列化
    """

    permissions = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = ['id', 'is_superuser', 'username', 'is_staff', 'is_active', 'groups', 'permissions']
        # 指定要包含关联模型的详细信息的深度。在这里，关联模型包括groups，depth=1表示将关联模型的一级详细信息也包含在序列化结果中。
        depth = 2

    def get_permissions(self, obj):
        # 获取用户属于的所有用户组
        groups = obj.groups.filter().first()
        if groups is None:
            return []
        permissions = groups.permissions.all()
        if permissions is None:
            return []
        permissions_list = [permission.codename for permission in permissions]
        return permissions_list


class UserListModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'username', 'is_superuser', 'is_staff', 'is_active']
